<template>
  <q-page class="q-pa-md">
    <q-btn class="float-right" color="primary" icon="arrow_back" outline title="返回" to="/" />
    <div class="q-pb-md text-h5">有单移库</div>
    <!--错误提示-->
    <q-banner class="text-white bg-red q-mb-sm" dense inline-actions v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn @click="serverErrorMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <q-stepper v-model="$d.workStep" ref="stepper" color="primary" flat :header-nav="false">
      <q-step :name="1" title="单号" icon="note" :done="$d.workStep>1">
        <div class="row q-col-gutter-sm col-12">
          <div class="col-12">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>移库单序号</span>
            <easy-input :disable="moveInfoLoadingState" @keyup.enter="validMoveId" v-model="$d.form.moveId"
              @update:model-value="validMoveId('clear')" :error="v$.moveId.$error" :error-message="e$(v$.moveId.$errors)"
              @focus="fx.ui.select"/>
          </div>
        </div>
        <div class="row q-pt-sm q-col-gutter-sm">
          <div class="col-6">
            <span>仓库</span>
            <easy-input readonly v-model="$d.moveInfo.whName" :loading="moveInfoLoadingState"/>
          </div>
          <div class="col-6">
            <span>货主</span>
            <easy-input readonly v-model="$d.moveInfo.storerAbbrName" :loading="moveInfoLoadingState"/>
          </div>
          <div class="col-6">
            <span>来源储区</span>
            <easy-input readonly v-model="$d.moveInfo.fZoneName" :loading="moveInfoLoadingState"/>
          </div>
          <div class="col-6">
            <span>目标储区</span>
            <easy-input readonly v-model="$d.moveInfo.tZoneName" :loading="moveInfoLoadingState"/>
          </div>
          <div class="col-6">
            <span>状态</span>
            <easy-input readonly :model-value="fx.fmt.fmtMoveState($d.moveInfo.moveState)" :loading="moveInfoLoadingState"/>
          </div>
          <div class="col-6">
            <span>计划移库日期</span>
            <easy-input readonly v-model="$d.moveInfo.expectedDt" :loading="moveInfoLoadingState"/>
          </div>
        </div>
      </q-step>
      <q-step :name="2" title="操作" icon="construction" :done="$d.workStep>2">
        <div class="row q-pt-sm q-col-gutter-sm">
          <div class="row q-col-gutter-sm col-12">
            <div class="col-6">
              <q-icon color="red" name="fas fa-asterisk" size="10px" />
              <span>移库单明细序号</span>
              <easy-input :disable="moveLineIdLoadingState" @keyup.enter="validMoveLineId" v-model="$d.form.moveLineId"
                @update:model-value="validMoveLineId('clear')" :error="v$move.moveLineId.$error"
                :error-message="e$(v$move.moveLineId.$errors)" @focus="fx.ui.select" ref="moveLineId"/>
            </div>
            <div class="col-6">
              <span>移库数量</span>
              <easy-input v-model="$d.form.qty" :loading="moveLineIdLoadingState" readonly/>
            </div>
          </div>
          <div class="row q-col-gutter-sm col-12">
            <div class="col-6">
              <q-icon color="red" name="fas fa-asterisk" size="10px" />
              <span>来源储位</span>
              <easy-input v-model="$d.form.fLoc" @focus="fx.ui.select" :error="v$move.fLoc.$error"
                :error-message="e$(v$move.fLoc.$errors)" ref="fLoc"
                @keyup.enter="focusHelper.onEntered(1)"/>
            </div>
            <div class="col-6">
              <q-icon color="red" name="fas fa-asterisk" size="10px" />
              <span>来源栈板(箱号)</span>
              <easy-input v-model="$d.form.fLpn" @focus="fx.ui.select" :error="v$move.fLpn.$error"
                :error-message="e$(v$move.fLpn.$errors)"
                :ref="el=>focusHelper.regRef(el, 2)" @keyup.enter="focusHelper.onEntered(2)"/>
            </div>
          </div>
          <div class="row q-col-gutter-sm col-12">
            <div class="col-6">
              <q-icon color="red" name="fas fa-asterisk" size="10px" />
              <span>目的储位</span>
              <easy-input v-model="$d.form.tLoc" @focus="fx.ui.select" :error="v$move.tLoc.$error"
                :error-message="e$(v$move.tLoc.$errors)"
                :ref="el=>focusHelper.regRef(el, 3)" @keyup.enter="focusHelper.onEntered(3)"/>
            </div>
            <div class="col-6">
              <q-icon color="red" name="fas fa-asterisk" size="10px" />
              <span>目的栈板(箱号)</span>
              <easy-input v-model="$d.form.tLpn" @focus="fx.ui.select" :error="v$move.tLpn.$error"
                :error-message="e$(v$move.tLpn.$errors)"
                :ref="el=>focusHelper.regRef(el, 4)" @keyup.enter="focusHelper.onEntered(4)"/>
            </div>
          </div>
          <div class="row q-col-gutter-sm col-12">
            <div class="col-6">
              <q-icon color="red" name="fas fa-asterisk" size="10px" />
              <span>批号或外部批号</span>
              <easy-input v-model="$d.form.lotOrVLot" @focus="fx.ui.select" :error="v$move.lotOrVLot.$error"
                :error-message="e$(v$move.lotOrVLot.$errors)"
                :ref="el=>focusHelper.regRef(el, 5)" @keyup.enter="focusHelper.onEntered(5)"/>
            </div>

          </div>
        </div>
      </q-step>
      <template v-slot:navigation>
        <div class="row q-pt-md q-col-gutter-sm">
          <!-- Step1的按钮 -->
          <div class="offset-6 col-6" v-show="$d.workStep===1">
            <q-btn :disable="!$d.isValidInvMove" class="full-width" color="primary" icon-right="arrow_forward"
              label="下一步" @click="$d.workStep=2" />
          </div>
          <!-- Step2的按钮 -->
          <div class="col-6" v-show="$d.workStep===2">
            <q-btn class="full-width" color="primary" icon="arrow_back" label="上一步" outline @click="$d.workStep=1" />
          </div>
          <div class="col-6" v-show="$d.workStep===2">
            <q-btn class="full-width" color="primary" icon-right="fas fa-sign-in-alt" label="确定移库"
              @click="doInvMoveWithNote" :loading="submittingState" />
          </div>
        </div>
      </template>
    </q-stepper>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'MoveWithNoteStd'
}
</script>
<script lang="ts" setup>

import {computed, reactive, ref} from 'vue'
import useVuelidate from '@vuelidate/core'
import {WmInvMove,WmInvMoveLine} from '@njt/wms/defs/inventory/invmove'
import {playErrorSound, playSuccessSound, playBeepSound} from '@njt/wms/helper/audio'
import _ from 'lodash'
import {QInput} from 'quasar'
import { useFocusNextHelper } from '@njt/foundation/hooks/focusHelper'

let serverErrorMessage = ref('')
let submittingState = ref(false)
let moveInfoLoadingState = ref(false)
let moveLineIdLoadingState = ref(false)

const $d = reactive({
  workStep: 1,
  isValidInvMove: false,
  form: {
    //移库单ID
    moveId: null,
    //移库单明细ID
    moveLineId: null,
    //来源储位
    fLoc: null,
    //来源栈板
    fLpn: null,
    //目的储位
    tLoc: null,
    //目的栈板
    tLpn: null,
    //批号
    lotOrVLot: null,
    //移库数量
    qty: null as number | null
  },
  moveInfo: {} as WmInvMove
})
const validators = $f.validators
const rules = {
  moveId: {
    required: validators.required,
    int32: validators.int32,
    greaterThan: validators.greaterThan(0)
  }
}
const rulesMoveLine = {
  moveLineId: {
    required: validators.required,
    int32: validators.int32,
    greaterThan: validators.greaterThan(0)
  },
  fLoc: {
    required: validators.required
  },
  fLpn: {
    required: validators.required
  },
  tLoc: {
    required: validators.required
  },
  tLpn: {
    required: validators.required
  },
  lotOrVLot: {
    required: validators.required
  }
}
const v$ = useVuelidate(rules, computed(() => $d.form), {$autoDirty: true})
const v$move = useVuelidate(rulesMoveLine, computed(() => $d.form), {$autoDirty: true})

const doInvMoveWithNote = function () {
  serverErrorMessage.value = ''
  void v$move.value.$validate()
    .then((valRes) => {
      if (valRes) {
        submittingState.value = true
        let pdaParam = _.cloneDeep($d.form)
        if (pdaParam.qty == null) pdaParam.qty = 0
        $f.axios
          .post<boolean>('/wms/inv/inventory/do-inv-move-by-pda', pdaParam)
          .then((resp) => {
            $d.form.moveLineId = null
            $d.form.fLoc = null
            $d.form.fLpn = null
            $d.form.tLoc = null
            $d.form.tLpn = null
            $d.form.lotOrVLot = null
            $d.form.qty = null
            v$move.value.$reset()
            if (resp.data) {
              $d.workStep = 1
              $f.ui.showNotifySucceeded(`移库单[${$d.form.moveId}]全部移库完成`)
              playSuccessSound()
              $d.form.moveId = null
              _.forIn($d.moveInfo, (value, key) => {
                $d.moveInfo[key] = null
              })
              $d.isValidInvMove = false
              v$.value.$reset()
            } else {
              //部分移库完成
              moveLineId.value && moveLineId.value.focus()
              $f.ui.showNotifySucceeded('有单移库成功')
              playBeepSound()
            }
          })
          .catch((err) => {
            playErrorSound()
            serverErrorMessage.value = $f.getAxiosErrMsg(err)
          })
          .finally(() => {
            submittingState.value = false
          })
      } else {
        playErrorSound()
      }
    })
}

const validMoveId = function (val?:string) {
  serverErrorMessage.value = ''
  $d.isValidInvMove = false
  _.forIn($d.moveInfo, (value, key) => {
    $d.moveInfo[key] = null
  })
  if (val==='clear') {
    return
  }
  void v$.value.$validate()
    .then((valRes) => {
      if (valRes) {
        moveInfoLoadingState.value = true
        $f.axios
          .get<WmInvMove>('/wms/inv/inventory/get-inv-move-by-id/'+$d.form.moveId)
          .then((resp) => {
            $d.moveInfo = resp.data
            $d.moveInfo.expectedDt = $f.fmt.dtFmtDateOnly($d.moveInfo.expectedDt)
            if ((resp.data.moveState as string) >= '9' || ((resp.data.moveState as string) === '0')) {
              serverErrorMessage.value = '移库单主档状态必须为“已审核”或“移库中”，才可以进行移库操作,该移库单状态不符合'
              playErrorSound()
            } else {
              $d.isValidInvMove = true
            }
          })
          .catch((err) => {
            playErrorSound()
            if (err.response?.status === 404) {
              serverErrorMessage.value = '该移库单ID不存在'
            } else {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            }
          })
          .finally(() => {
            moveInfoLoadingState.value = false
          })
      } else {
        playErrorSound()
      }
    })
}
const validMoveLineId = function (val?: string) {
  serverErrorMessage.value = ''
  $d.form.qty = null
  if (val === 'clear') return
  moveLineIdLoadingState.value = true
  $f.axios
    .get<WmInvMoveLine>('/wms/inv/inventory/get-inv-moveline-by-id/'+$d.form.moveLineId)
    .then((resp) => {
      $d.form.qty = resp.data.qty
      fLoc.value && fLoc.value.focus()
    })
    .catch(() => {
      // ignore
    })
    .finally(() => {
      moveLineIdLoadingState.value = false
    })
}

const fLoc = ref<QInput | null>(null)
const moveLineId = ref<QInput | null>(null)
const fx = $f
const e$ = $f.getFieldErrStr
const focusHelper = useFocusNextHelper()
focusHelper.regRef(fLoc, 1)
</script>

<style scoped>

</style>
